/**
 * @author: zhazhjie
 * @email: zhazhjie@vip.qq.com
 * @date: 2018-11-05 14:20:38
 * @version: 1.0
 */
import {Validate} from "@/config/validate";

const storeCache = Object.create(null);

/**
 * 设置本地存储
 * @param key {String}
 * @param value {*}
 * @param localFlag
 */
export function setStore(key, value, localFlag = false) {
    if (localFlag) {
        if (Validate.isEmpty(value)) {
            uni.removeStorageSync(key);
        } else {
            uni.setStorageSync(key, value);
        }
    } else {
        /* #ifdef H5 */
        if (Validate.isEmpty(value)) {
            sessionStorage.removeItem(key);
        } else {
            sessionStorage.setItem(key, JSON.stringify(value));
        }
        /* #endif */

        /* #ifdef MP-WEIXIN */
        if (Validate.isEmpty(value)) {
            delete storeCache[key];
        } else {
            storeCache[key] = value;
        }
        /* #endif */
    }
}

/**
 * 获取本地存储
 * @param key {String}
 * @param localFlag
 * @returns {*}
 */
export function getStore(key, localFlag = false) {
    if (localFlag) {
        return uni.getStorageSync(key);
    } else {
        /* #ifdef H5 */
        try {
            return JSON.parse(sessionStorage.getItem(key) || 'null');
        } catch (e) {
        }
        /* #endif */

        /* #ifdef MP-WEIXIN */
        return storeCache[key];
        /* #endif */
    }
}

/**
 * 计算坐标点距离，单位km
 * @param lat1
 * @param lng1
 * @param lat2
 * @param lng2
 * @returns {string}
 */
export function getDistance(lat1, lng1, lat2, lng2) {
    let rad = (d) => {
        return d * Math.PI / 180.0;
    };
    let radLat1 = rad(lat1);
    let radLat2 = rad(lat2);
    let a = radLat1 - radLat2;
    let b = rad(lng1) - rad(lng2);
    let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    s = s.toFixed(1);
    // console.log('经纬度计算的距离:' + s);
    return s;
}

/**
 * 是否在微信小程序
 * @returns {boolean}
 */
export function isInWxMa() {
    /* #ifdef MP-WEIXIN */
    return true;
    /* #endif */
}

/**
 * 获取appId
 * @returns {string}
 */
export function getAppId() {
    /* #ifdef H5 */
    return '';
    /* #endif */
    /* #ifdef MP-WEIXIN */
    let accountInfo = uni.getAccountInfoSync();
    let {appId = ''} = accountInfo.miniProgram || {};
    return appId;
    /* #endif */
    /* #ifdef MP-ALIPAY */
    let appIdSync = my.getAppIdSync();
    return appIdSync.appId;
    /* #endif */
}

/**
 * 格式化参数
 * @param str
 * @returns {{}}
 */
export function formatParams(str) {
    if (!str) return {};
    str = decodeURIComponent(str);
    let index = str.indexOf('?');
    if (index === -1) return {};
    let search = str.substring(index + 1);
    let results = {};
    let searchAry = search.split('&');
    searchAry.forEach(item => {
        let val = item.split('=');
        results[val[0]] = decodeURIComponent(val[1]);
    });
    return results;
}

/**
 * 解析参数（包含普通二维码拉起微信小程序）
 * @param options
 * @returns {{}}
 */
export function parseOptions(options) {
    let {q} = options || {};
    if (q) {
        let params = formatParams(q);
        return {...options, ...params};
    } else {
        return options;
    }
}

/**
 * 禁止分享
 */
export function disableShare() {
    /* #ifdef H5 */
    if (Validate.isAlipayClient()) {
        ap.hideOptionButton();
    } else if (window.__wxjs_environment === 'miniprogram') {
        wx.hideShareMenu();
    }
    /* #endif */
    /* #ifdef MP-WEIXIN */
    uni.hideShareMenu();
    /* #endif */
}

export function isIOS() {
    let {system = ''} = wx.getSystemInfoSync();
    return system.toLowerCase().includes('ios');
}

export function compareVersion(v1, v2) {
    v1 = v1.split('.');
    v2 = v2.split('.');
    const len = Math.max(v1.length, v2.length);

    while (v1.length < len) {
        v1.push('0');
    }
    while (v2.length < len) {
        v2.push('0');
    }

    for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i]);
        const num2 = parseInt(v2[i]);

        if (num1 > num2) {
            return 1;
        } else if (num1 < num2) {
            return -1;
        }
    }

    return 0;
}

/**
 * 日期格式化
 */
export function dateFormat(date, format = 'yyyy-MM-dd hh:mm:ss') {
    if (date != 'Invalid Date') {
        var o = {
            'M+': date.getMonth() + 1, //month
            'd+': date.getDate(), //day
            'h+': date.getHours(), //hour
            'm+': date.getMinutes(), //minute
            's+': date.getSeconds(), //second
            'q+': Math.floor((date.getMonth() + 3) / 3), //quarter
            'S': date.getMilliseconds() //millisecond
        };
        if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
            (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp('(' + k + ')').test(format))
                format = format.replace(RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] :
                        ('00' + o[k]).substr(('' + o[k]).length));
        return format;
    }
    return '';
}
